package com.huluobo.a2201mvvm_imdemo.login;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2201mvvm_imdemo.IMApp;
import com.huluobo.a2201mvvm_imdemo.MainActivity;
import com.huluobo.a2201mvvm_imdemo.R;
import com.huluobo.a2201mvvm_imdemo.databinding.ActivityLoginBinding;
import com.huluobo.a2201mvvm_imdemo.mvvm.BaseMVVMActivity;
import com.huluobo.a2201mvvm_imdemo.register.RegisterActivity;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

public class LoginActivity extends BaseMVVMActivity<ActivityLoginBinding, LoginViewModel> {

    @Override
    protected void initData() {
        viewModel.success.observe(this, loginUserBean -> {
            //登录成功关闭进度条
            dismissProgressDialog();
            ToastUtils.showLong("登录成功:" + loginUserBean.getUsername());
            SPUtils.getInstance().put("username", loginUserBean.getUsername());
            SPUtils.getInstance().put("password", loginUserBean.getPassword());
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        });

        viewModel.failed.observe(this, s -> {
            dismissProgressDialog();
            ToastUtils.showLong("登录失败:" + s);
        });
    }

    @Override
    protected void initView() {
        //拿到头布局的title,赋值
        dataBinding.loginHeader.headerTitle.setText("登录");

        //触发登录,调用ViewModel中的登录方法
        dataBinding.loginToLogin.setOnClickListener(v -> {
            if (dataBinding.loginUsername.getText().toString().matches(IMApp.REGEX_USERNAME)) {
                if (dataBinding.loginPassword.getText().toString().matches(IMApp.REGEX_PASSWORD)) {
                    //弹出进度条进行加载
                    showProgressDialog("正在登录...");
                    viewModel.login(
                            dataBinding.loginUsername.getText().toString(),
                            dataBinding.loginPassword.getText().toString()
                    );
                } else {
                    dataBinding.loginPassword.setError("密码不匹配,需要为3-20位数字");
                }
            } else {
                dataBinding.loginUsername.setError("用户名不匹配,需要为3-20字符,首字符为英文");
            }
        });

        dataBinding.loginToRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected Class<LoginViewModel> getViewModel() {
        return LoginViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }
}